﻿using System;
using System.Collections.Generic;
using System.Collections;
using System.Linq;
using System.Web;
using System.Data;
using System.Text;
using System.IO;

namespace Aandelendelen.Obs
{
	public class BaseDataTable : DataTable, ICollection, IEnumerable
	{
		protected string csvHeader = "";

		public BaseDataTable()
			: base()
		{
		}

		public BaseDataTable(string tableName)
			: base(tableName)
		{
		}

		public void SaveAsCSV(TextWriter writer)
		{
			writer.WriteLine(this.csvHeader);

			foreach (DataRow row in this.Rows)
			{
				StringBuilder str = new StringBuilder(256);

				object[] values = row.ItemArray;

				for (int i = 0; i < values.Length; i++)
				{
					if (i != 0)
						str.Append(", ");

					str.Append(values[i].ToString().Replace(',', '.'));
				}

				writer.WriteLine(str.ToString());
			}
		}

		#region ICollection methods
		public bool IsSynchronized
		{
			get
			{
				return false;
			}
		}

		public object SyncRoot
		{
			get
			{
				return this;
			}
		}

		public void CopyTo(Array array, int index)
		{
			if (array == null) throw new ArgumentNullException();
			if (index < 0) throw new ArgumentOutOfRangeException();

			int count = this.Count;
			if (index + count > array.Length) throw new ArgumentException();

			for (int i = 0; i < count; i++)
			{
				array.SetValue(this.Rows[i], index++);
			}
		}

		public int Count
		{
			get
			{
				return this.Rows.Count;
			}
		}

		public IEnumerator GetEnumerator()
		{
			return (IEnumerator)new Enumerator(this.Rows);
		}

		#endregion

		private class Enumerator
		{
			DataRowCollection rows = null;
			int index = -1;
			DataRow current = null;

			public Enumerator(DataRowCollection rows)
			{
				this.rows = rows;

				this.Reset();
			}

			public void Reset()
			{
				this.index = -1;
				this.current = null;
			}

			public object Current
			{
				get
				{
					if (this.current != null)
						return this.current;
					else
						throw new InvalidOperationException();
				}
			}

			public bool MoveNext()
			{
				this.index++;
				if (this.index < this.rows.Count)
				{
					this.current = this.rows[this.index];
					return true;
				}
				else
				{
					this.current = null;
					return false;
				}
			}
		}
	}
}